{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "757c0180",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'generator'>\n",
      "<generator object <genexpr> at 0x0000014D75B53B30>\n"
     ]
    }
   ],
   "source": [
    "#声明生成器\n",
    "g1 =(x * x for x in range(10) )\n",
    "\n",
    "print(type(g1))\n",
    "print(g1)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "1bbe668f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "4\n",
      "9\n",
      "16\n",
      "25\n",
      "36\n",
      "49\n",
      "64\n",
      "81\n"
     ]
    }
   ],
   "source": [
    "#遍历生成器的两种方式\n",
    "print(next(g1))\n",
    "print(next(g1))\n",
    "\n",
    "for i in g1:\n",
    "    print(i)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "89bb96d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "g2的类型是：<generator object odds at 0x0000014D75BB0190>\n",
      "step 1\n",
      "1\n",
      "step 3\n",
      "3\n",
      "step 5\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "#通过生成器函数的方式声明生成器\n",
    "def odds():\n",
    "    print('step 1')\n",
    "    yield 1\n",
    "    print('step 3')\n",
    "    yield 3\n",
    "    print('step 5')\n",
    "    yield 5\n",
    "\n",
    "g2 = odds()\n",
    "print(\"g2的类型是：%s\" % g2)\n",
    "for x in g2:\n",
    "    print(x)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
